<?php
namespace app\admin\service;

use app\admin\model\RolePermissionModel;
use app\admin\model\UserModel;
use app\admin\model\UserRoleModel;
use app\admin\model\PermissionModel;

class UserService
{
    /**
     * 当前Service所对应的Model
     * @var \app\admin\model\UserModel
     */
    private $model;

    public function __construct()
    {
        $this->model = new UserModel;
    }

    public function detail( $where = [], $field="*" )
    {
        // 用户角色
        $userRoleModel = new UserRoleModel();

        $info = $this->model->getInfoByWhere(
            $where,
            $field
        );
        if( empty($info) ){
            return [];
        }
        $userRole = $userRoleModel->getInfoByWhere([
            'user_id' => $info['id']
        ],'
            role_id
        ');

        $permissionsData = $this->getPermissions( $userRole['role_id'] );
        $info['role'] = $permissionsData;
        return $info;
    }

    public function edit( $id, $data=[] )
    {
        $res = $this->model->editInfoById(
            $id,
            $data
        );
        return $res;
    }

    /**
     * 获取用户相关权限
     * @param $roleId
     * @return array
     */
    private function getPermissions( $roleId )
    {
        $rolePermissionModel = new RolePermissionModel;
        $permissionModel = new PermissionModel;
        $permissions = $rolePermissionModel->getDataByWhere([
            'role_id' => $roleId
        ],'
            permission_id
        ');
        $permissionsIds = array_column($permissions,'permission_id');
        $permissionsList = $permissionModel->whereIn('id',$permissionsIds
        )->where([
            'status' => 1,
            'is_delete' => 1
        ])->field('
            id,
            title,
            pid,
            action
        ')->select()->toArray();
        $parentData = [];
        $childrenData = [];
        foreach ($permissionsList as &$item) {
            if( $item['pid'] == 0 ){
                $item['permissionName'] = $item['title'];
                $item['permissionId'] = $item['action'];
                $parentData[] = $item;
            }else{
                $childrenData[$item['pid']][] = $item;
            }
        }
        foreach ($parentData as &$parentItem) {
            $parentItem['actions'] = [];
            if( isset($childrenData[$parentItem['id']]) ){
                $parentItem['actions'] = $childrenData[$parentItem['id']];
            }
        }
        $list['permissions'] = $parentData;
        return $list;
    }

}